package com.lumlord.convert;


import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.lang.Nullable;
import org.springframework.util.StreamUtils;
 
public class StringConverter extends AbstractHttpMessageConverter<String> {
    /**
     * 定义字符编码，防止乱码
     */
	public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
    /**
     * 新建自定义的媒体类型
     */
    public StringConverter(){
        super(new MediaType("application", "*+json",DEFAULT_CHARSET));
    }
    
     
 
    /**
     * 表明只处理DemoObj这个类
     */
    @Override
    protected boolean supports(Class<?> aClass) {
        return String.class.isAssignableFrom(aClass);
    }
 
 
    @Override
	public boolean canRead(Class<?> clazz, MediaType mediaType) {
		if(clazz.equals(String.class)) {
			return true;
		}
		return super.canRead(clazz, mediaType);
	}

	/**
     * 重写writeInternal，处理如何输出数据到response
     */
    @Override
    protected void writeInternal(String demoObj, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
       
        StreamUtils.copy(demoObj, DEFAULT_CHARSET, httpOutputMessage.getBody());
    }

	@Override
	protected String readInternal(Class<? extends String> clazz, HttpInputMessage inputMessage)
			throws IOException, HttpMessageNotReadableException {
		 String temp=StreamUtils.copyToString(inputMessage.getBody(),DEFAULT_CHARSET);
	        return new String(temp);
	}
}